import Koa, { Middleware } from "koa";
import Router from "koa-router";
import bodyParser from "koa-bodyparser";
import serve from "koa-static";
import db from "./db";
const path = require("path");

interface Todo {
  id: string;
  text: string;
  completed: boolean;
  ctime: number;
  mtime: number;
}

const app = new Koa();
const router = new Router();

app.use(serve(path.join(__dirname, "../../client/dist")));

router.get("/api/todos", async (ctx, next) => {
  ctx.body = db.getAll();
});

router.post("/api/todos", async (ctx, next) => {
  if (typeof ctx.request.body === "object" && ctx.request.body !== null) {
    const todo = ctx.request.body as Todo;
    db.add(todo);
    ctx.body = todo;
  } else {
    ctx.body = "错误格式";
  }
});

router.put("/api/todos/:id", async (ctx, next) => {
  const id = ctx.params.id;
  console.log(id);
  const todo = db.get(id);
  console.log(todo);
  if (todo) {
    if (typeof ctx.request.body === "object" && ctx.request.body !== null) {
      const todo = ctx.request.body as Todo;
      console.log(todo);
      db.update(todo);
      ctx.body = todo;
    } else {
      ctx.body = "错误格式";
    }
  } else {
    ctx.status = 404;
  }
});

router.delete("/api/todos/:id", async (ctx, next) => {
  const id = ctx.params.id;
  const todo = db.get(id);
  if (todo) {
    db.delete(id);
    ctx.body = todo;
  } else {
    ctx.status = 404;
  }
});

app.use(bodyParser());
app.use(router.routes());

app.listen(3001, () => {
  console.log("Server is running on http://localhost:3001");
});
